#include "Stack.h"

#define _CRT_SECURE_NO_WARNINGS 1

void StackInit(Stack* ps)
{
	assert(ps);
	ps->top = ps->capacity = 0;
	ps->a = NULL;
}

void StackPushBack(Stack* ps, SDataType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		SDataType newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SDataType* tmp=(SDataType*)relloc(ps->a,newcapacity*sizeof(SDataType));
		if (tmp == NULL)
		{
			perror("relloc fail");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
	ps->a[ps->top]=x;
	ps->top++;
}

void StcakPop(Stack* ps)
{
	assert(!StackEmpty(ps));
	assert(ps);
	ps->top--;
}

bool StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top==0;
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	ps->top = ps->capacity = 0;
	free(ps->a);
	ps->a = NULL;
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}

SDataType StackTop(Stack* ps)
{
	return ps->a[ps->top-1];
}
